<template>
  <div class="page2">
    <div class="device-wrapper">
      <el-row class="row-bg" :gutter="20">
        <el-col
          v-for="(item, i) in device"
          :key="i"
          :class="currentDevice.peerId == item.device.peerid ? 'on' : ''"
          @click="changeDevice(item.device)"
        >
          <div class="item">
            <div>
              <div class="name">
                {{ item.device.device_name }}
              </div>
              <div class="brief" style="margin-top: 8px">
                {{ item.device.peerid }}
              </div>
              <div class="brief">
                <span>IP: {{ item.device.ip }}</span>
                <n-divider vertical />
                <span>
                  {{ item.device.ip_info.province }}
                  {{ item.device.ip_info.city }}
                  {{ item.device.ip_info.isp }}
                </span>
              </div>
            </div>
            <div class="disk">
              <n-space>
                <span v-for="(disk, j) in item.partitions" :key="j">
                  <!-- {{ disk.partition }} -->
                  <n-progress
                    type="dashboard"
                    gap-position="bottom"
                    :border-radius="70"
                    :percentage="(disk.partition.used * 100) / disk.partition.capacity"
                  >
                    <template #default>
                      <div class="percentage-value">
                        {{
                          ((disk.partition.used * 100) / disk.partition.capacity).toFixed(
                            2
                          )
                        }}%
                      </div>
                      <div class="percentage-label">磁盘{{ j + 1 }}</div>
                    </template>
                  </n-progress>
                </span>
              </n-space>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="search-wrapper">
      <n-input v-model:value="url" placeholder="请输入磁力链接" class="input-with-select">
        <template #prefix>
          <span style="padding: 0 10px">磁力连接</span>
        </template>
        <template #suffix>
          <n-button @click="handleUrlResolve" type="primary">提交</n-button>
        </template>
      </n-input>
    </div>
    <div id="taskinfo-list" ref="loadingBarTargetRef">
      <div v-if="taskData?.peer">
        <n-list hoverable :show-divider="false" class="task-list">
          <n-list-item v-for="(item, i) in taskData.peer.tasks" :key="i">
            <n-thing class="task-item">
              <template #header>
                <div class="task-title-wrapper">
                  <n-tag
                    :type="completeTaskState(item.data.state).type"
                    size="small"
                    :bordered="false"
                    round
                  >
                    {{ completeTaskState(item.data.state).label }}
                  </n-tag>
                  <div class="name">
                    {{ item.data.name }}
                  </div>
                </div>
              </template>
              <template #header-extra>
                <n-space>
                  <!-- <template> -->
                  <i
                    v-if="item.data.state == 0"
                    @click="handlePauseTask(item.data)"
                    class="iconfont icon-poweroff-circle-fill"
                  ></i>
                  <i
                    v-else-if="item.data.state == 9"
                    @click="handleStartTask(item.data)"
                    class="iconfont icon-play-circle-fill"
                  ></i>
                  <!-- </template> -->

                  <n-dropdown
                    trigger="hover"
                    :options="actionOptions"
                    @select="(key) => handleSelect(key, item.data)"
                  >
                    <i class="iconfont icon-icon_workset"></i>
                  </n-dropdown>
                </n-space>
              </template>
              <div class="process-wrapper" v-if="item.data.state == 0">
                <n-progress
                  type="line"
                  :percentage="item.data.progress / 100"
                  processing
                  :indicator-placement="'inside'"
                  :height="12"
                />

                <n-space>
                  <n-tooltip trigger="hover">
                    <template #trigger>
                      <span>{{ formatTime(item.data.remainTime) }}</span>
                    </template>
                    剩余时间
                  </n-tooltip>

                  <span>{{ completeSpeed(item.data.speed) }}</span>
                </n-space>
              </div>

              {{ item.data.path }}
              <template #footer>
                <n-space class="info">
                  <span>
                    创建时间：{{
                      dayjs.unix(item.data.createTime).format("YYYY/MM/DD HH:mm:ss")
                    }}
                  </span>
                  <n-divider vertical />
                  <span>存储：{{ formatFileSize(item.data.size) }}</span>
                  <n-divider vertical />
                  <template v-if="item.data.state == 11">
                    <span
                      >完成时间：{{
                        dayjs.unix(item.data.completeTime).format("YYYY/MM/DD HH:mm:ss")
                      }}</span
                    >
                  </template>
                  <!-- <n-divider vertical />
                  <span>耗时：{{ formatTime(item.data.downTime) }}</span> -->
                </n-space>
              </template>
            </n-thing>
          </n-list-item>
        </n-list>
      </div>
    </div>
    <n-drawer
      v-model:show="active"
      placement="bottom"
      :trap-focus="false"
      :block-scroll="false"
      to="#taskinfo-list"
      default-height="100%"
      resizable
    >
      <n-drawer-content>
        <template #header>
          <div class="task-title-wrapper">
            <n-tag type="success" size="small" round>
              {{ formatFileSize(urlResolveResult.taskInfo.size) }}
            </n-tag>
            <div class="name">{{ urlResolveResult.taskInfo.name }}</div>
            <div>
              <n-space>
                <n-button
                  :disabled="
                    urlResolveResult.taskInfo.subList.filter((x) => x.selected === true)
                      .length == 0
                  "
                  quaternary
                  @click="handleCreateBatchTaskWithUrlResolve"
                >
                  开始下载
                </n-button>

                <n-button type="tertiary" quaternary @click="active = false">
                  <i
                    style="font-size: 20px; cursor: pointer"
                    class="iconfont icon-cuowu1"
                  ></i>
                </n-button>
              </n-space>
            </div>
          </div>
        </template>
        <n-list>
          <n-list-item
            class="task"
            v-for="(item, i) in urlResolveResult.taskInfo.subList"
            :key="i"
          >
            <template #suffix>
              <div class="size">{{ formatFileSize(item.size) }}</div>
            </template>
            <div>
              <n-checkbox v-model:checked="item.selected">{{ item.name }} </n-checkbox>
            </div>
          </n-list-item>
        </n-list>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import dayjs from "dayjs";
import {
  NDrawer,
  NCheckbox,
  NSpace,
  NList,
  NListItem,
  NTag,
  NDrawerContent,
  NButton,
  NProgress,
  NDivider,
  NInput,
  useMessage,
  NThing,
  NTooltip,
  NDropdown,
} from "naive-ui";
import wankeyunApi from "@/api-services/apis/wankeyun";
import bus from "vue3-eventbus";
import useClipboard from "vue-clipboard3";
const { toClipboard } = useClipboard();

const device = ref<any>({});
const url = ref("");
const currentDevice = ref<any>({});
const urlResolveResult = ref<any>({});
const active = ref(false);
const message = useMessage();
const taskData = ref<any>({});
const actionOptions = ref<any[]>([]);
actionOptions.value = [
  {
    label: "复制链接",
    key: "copy",
  },
  {
    type: "divider",
    key: "d1",
  },
  {
    label: "删除任务",
    key: "delete",
  },
  {
    label: "删除任务及文件",
    key: "deleteFile",
  },
];
onMounted(() => {
  bus.on("玩客云任务", (data) => {
    console.log(data);
    taskData.value = data.data;
  });
  bus.on("玩客云下载完成", (data) => {
    console.log(data);
  });
});

onUnmounted(() => {
  bus.off("玩客云任务");
  bus.off("玩客云下载完成");
});
async function getAllDevice() {
  device.value = await wankeyunApi.GetAllDevice();
  currentDevice.value = device.value[0];
}
getAllDevice();

async function handleUrlResolve() {
  message.loading("链接解析中，请稍后...", {
    closable: true,
    duration: 0,
  });
  urlResolveResult.value = await wankeyunApi.UrlResolve({
    peerid: currentDevice.value.peerId,
    url: url.value,
  });
  active.value = true;
  message.destroyAll();
}

async function handleCreateBatchTaskWithUrlResolve() {
  let subTaskId = urlResolveResult.value.taskInfo.subList
    .filter((x) => x.selected === true)
    .map((x) => x.id);
  if (subTaskId.length == 0) {
    message.error("请勾选需要下载的文件");
    return;
  }
  await wankeyunApi.CreateBatchTaskWithUrlResolve({
    peerid: currentDevice.value.peerId,
    path: "",
    urlResolveResult: urlResolveResult.value,
    subTaskId: subTaskId,
  });

  active.value = true;
}

function changeDevice(device) {
  currentDevice.value = device;
}

function completeTaskState(state) {
  let data = {
    type: <"default" | "error" | "primary" | "info" | "success" | "warning">"info",
    label: "加载中",
  };
  switch (state) {
    case 0:
      data = {
        type: "info",
        label: "下载中",
      };
      break;
    case 9:
      data = {
        type: "warning",
        label: "已暂停",
      };
      break;
    case 11:
      data = {
        type: "success",
        label: "已完成",
      };
      break;

    default:
      break;
  }
  return data;
}

function completeSpeed(speed) {
  return formatFileSize(speed) + "/S";
}

function formatFileSize(fileSize) {
  if (fileSize < 1024) {
    return fileSize + "B";
  } else if (fileSize < 1024 * 1024) {
    var temp = fileSize / 1024;
    return temp.toFixed(2) + "KB";
  } else if (fileSize < 1024 * 1024 * 1024) {
    var temp = fileSize / (1024 * 1024);
    return temp.toFixed(2) + "MB";
  } else {
    var temp = fileSize / (1024 * 1024 * 1024);
    return temp.toFixed(2) + "GB";
  }
}

function formatTime(time) {
  return (time / 60 / 60).toFixed(2) + "H";
}

function handleSelect(key: string | number, task) {
  switch (key) {
    case "delete":
      handleDeleteTask(task, false);
      break;
    case "deleteFile":
      handleDeleteTask(task, true);
      break;
    case "copy":
      toClipboard(task.url);
      message.success("链接已复制");
      break;
    default:
      break;
  }
}

async function handlePauseTask(task) {
  await wankeyunApi.PauseTask({
    peerid: currentDevice.value.peerId,
    id: task.id,
    state: task.state,
    type: task.type,
  });
}
async function handleStartTask(task) {
  await wankeyunApi.StartTask({
    peerid: currentDevice.value.peerId,
    id: task.id,
    state: task.state,
    type: task.type,
  });
}
async function handleDeleteTask(task, deleteFile: boolean) {
  await wankeyunApi.DeleteTask({
    peerid: currentDevice.value.peerId,
    id: task.id,
    state: task.state,
    type: task.type,
    deleteFile: deleteFile,
  });
}
</script>

<style lang="scss" scoped>
.page2 {
  display: flex;
  flex-direction: column;
  .device-wrapper {
    // background-color: #fff;
    ::v-deep(.n-progress) {
      width: 70px;
      .n-progress-custom-content {
        display: block;
        text-align: center;
      }
    }
    .el-col {
      padding: 5px;
    }

    .item {
      display: flex;
      padding: 10px;

      > :first-child {
        flex: 1;
      }
      .name {
        font-size: 1.2rem;
      }
      .brief {
        color: #999;
      }
    }
  }
  .search-wrapper {
    ::v-deep(.n-input) {
      border-left: 0;
      border-right: 0;
      border-radius: 0;
      background-color: transparent;
      .n-input-wrapper {
        padding: 0;
      }
    }
  }
  //链接解析结果
  #taskinfo-list {
    flex: 1;
    position: relative;
    ::v-deep(.n-drawer-header__main) {
      width: 100%;
    }
    .task-title-wrapper {
      display: flex;
      align-items: center;
      .name {
        flex: 1;
        padding: 0 10px;
      }
    }
    .task {
      .size {
        width: 90px;
        text-align: right;
      }
    }
    .n-list {
      background-color: transparent;
    }
  }

  .task-list {
    li {
      border-bottom: 1px solid rgb(0 0 0 / 5%);
      border-radius: 0;
    }

    //任务列表
    .task-item {
      .task-title-wrapper {
        display: flex;
        align-items: center;
        .name {
          flex: 1;
          padding: 0 10px;
        }
      }
      .process-wrapper {
        display: flex;
        align-items: center;
        .n-progress {
          flex: 1;
          margin-right: 10px;
        }
      }
      .info {
        font-size: 0.8rem;
      }
    }
  }
}
</style>
